const momentTable = require('../models/momentTable');
const userTable = require('../models/userTable');
const commentTable = require('../models/commentTable');
const inspirecloud = require('@byteinspire/api');
const ObjectId = inspirecloud.db.ObjectId;

class momentService {
    
    async listAll() {
        const all = await momentTable.where().find();
        return all;
    }

    
    async create(moment) {
        return await momentTable.save(moment);
    }


    async delete(id) {
        const result = await momentTable.where({_id: ObjectId(id)}).delete();
        if (result.deletedCount === 0) {
          const error = new Error(`moment:${id} not found`);
          error.status = 404;
          throw error;
        }
    }


    async update(id, updater) {
        const moment = await momentTable.where({_id: ObjectId(id)}).findOne();
        if (!moment) {
          const error = new Error(`moment:${id} not found`);
          error.status = 404;
          throw error;
        }
        Object.assign(moment, updater);
        await momentTable.save(moment);
    }

    //点赞
    async addLike(newsID, userID) {
        const news = await momentTable.where({_id: ObjectId(newsID)}).findOne();
        if (!news) {
            const error = new Error(`lile:${newsID} not found`);
            error.status = 404;
            throw error;
        }
        news.favor_count.push(userID);
        await momentTable.save(news)
    }

    //取消点赞
    async cancelLike(newsID, userID) {
        const news = await momentTable.where({_id: ObjectId(newsID)}).findOne();
        if (!news) {
            const error = new Error(`cancelLile:${newsID} not found`);
            error.status = 404;
            throw error;
        }
        news.favor_count.remove(userID);
        await momentTable.save(news)
    }

    //获取动态详情
    async getNewsDetail(newsID) {
        var newsDetail = await momentTable.where({_id: ObjectId(newsID)}).findOne();
        // const user = await userTable.where({_id: ObjectId(newsDetail.userID)});
        // newsDetail.user = user;
        console.log(newsDetail);
        const comment = await commentTable.where({momentID: ObjectId(newsID),depth: 1}).find();
        newsDetail.comment = comment;
        return newsDetail;
    }
}

module.exports = new momentService();